/*
 * bill_console.cpp
 *
 *  Created on: Dec 26, 2013
 *      Author: killerg
 */

/*
 * console_cmd_handler.cpp
 *
 *  Created on: Nov 13, 2013
 *      Author: killerg
 */

#include "bill_deps.h"
#include "bill_console.h"
#include "bill.h"
#include "bill_cfg.h"
#include "code.h"
#include "share/msg.h"
#include "share/clock.h"

std::string cmd_mask(Arg &arg, void* dummy) {
    g_bill.console->_mask_s = get_int_arg(arg, "-m", E|W|I|C);
    return "success";
}

std::string cmd_shut(Arg &arg, void* dummy) {
    g_bill.svcdata->shut = true;
    return "success";
}

std::string cmd_codereload(Arg &arg, void* dummy) {
	double start = my_clock_t::get_time();
	bool res = g_bill.code->reload_code();
	double last = my_clock_t::get_time() - start;

    return fmt_cstr("codereload %s in %f seconds", res ? "success" : "failed", last);

}

std::string cmd_notice(Arg &arg, void* dummy) {
	string msg = get_str_arg(arg, "-m", "");
	if (msg.empty())
		return "empty msg";

	const char* cmsg = "notice -m 下午3点关服，玩得开心";
	puts(cmsg);

	puts(msg.c_str());
	g_svrmgr->serverinfos.for_each([msg](int id, server_info_t* &info){
		if (!info || !info->sess)
			return;

	    CREATE_SB_BMSG(BNotice, notice);
	    notice->set_notice(msg);
	    info->sess->send_msg(___msg);
	});

	return "success";
}

std::string cmd_log(Arg &arg, void* dummy) {
	g_bill.cfg->trace = !g_bill.cfg->trace;

	return g_bill.cfg->trace ? "log_on" : "log_off";
}

std::string cmd_reward(Arg &arg, void* dummy) {
    string account = get_str_arg(arg, "-a", "");
    int32_t serverid = get_int_arg(arg, "-s", -1);
    int32_t rewardid = get_int_arg(arg, "-r", -1);
    string content = get_str_arg(arg, "-c", "");

    if (serverid < 0) {
    	return "no server name";
    }

    if (rewardid < 0) {
    	return "no rewardid";
    }

    auto svrinfo = g_svrmgr->serverinfos.get(serverid);
    if (NULL == svrinfo || NULL == svrinfo->sess) {
        return "no server";
    }

    auto playerinfo = g_svrmgr->get_player_info(serverid, account);
    if (NULL == playerinfo) {
    	return "no account";
    }

    CREATE_SB_BMSG(BReward, reward);
    reward->set_account(account);
    reward->set_playerid(playerinfo->playerid);
    reward->set_reward(rewardid);
    reward->set_content(content);
    svrinfo->sess->send_msg(___msg);


    return "success";
}


bool bill_console_t::init() {
    if (!console_t2::init_net())
        return false;

    bool rtv = true;
    rtv = rtv && console_t2::reg("shut", "", cmd_shut);
    rtv = rtv && console_t2::reg("mask", "m:", cmd_mask);
    rtv = rtv && console_t2::reg("reward", "a:s:r:c:", cmd_reward);
    rtv = rtv && console_t2::reg("codereload", "", cmd_codereload);
    rtv = rtv && console_t2::reg("notice", "m:", cmd_notice);
    rtv = rtv && console_t2::reg("log", "", cmd_log);

    _mask_f = E|W|I;
    _mask_s = E|W|I|C;

    return rtv;
}

void bill_console_t::destroy() {
    console_t2::destroy();
}

void bill_console_t::update() {
    console_t2::update();
}
